import type { RouteRecordRaw } from "vue-router";
import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
// import type { UserInfoState } from './interface';
import {ElMessage} from 'element-plus'
import {staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'
import userinfoApi, { type userinfoModel } from '@/api/userinfo';
import router from "@/router";
import { cloneDeep } from 'lodash'

//参数一: 动态路由 - 动态路由就是需要筛选的路由
//参数二: 用户信息返回的当前用户可以看到的菜单
const filterRoutesHandler = (routes: RouteRecordRaw[], routesName: string[]) => {
  // 进入当前函数之后,拿着一级路由在筛选,筛选出来的结果也只是对一级路由进行的
  // 展示只要一级路由有，二级路由就都会展示
  let result = routes.filter(route => { // routes 是路由数组,route是每一个路由
    if (route.children) { // 如果当前路由有子路由,那么对子路由进行筛选,得到一个新的数组,重新赋值给 route.children
      route.children = filterRoutesHandler(route.children, routesName); // 递归调用
    }
    return routesName.includes(route.name as string); //判断用户数据返回的菜单权限是不是包含当前路由的name属性
  })
  return result;
}

// 动态注册路由
const addRoutes = (allRoutes: RouteRecordRaw[]) => {
  allRoutes.forEach(route => {
    router.addRoute(route); 
  })
}





interface UserInfoState { 
  token: string,
  userinfo: userinfoModel,
  menuRoutes: RouteRecordRaw[]
}

const initUserinfo = (): userinfoModel => ({
  avatar: '',
  name: '',
  buttons: [],
  roles: [],
  routes: []
}) 

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

	state: (): UserInfoState => ({
    token: getToken() as string,
    userinfo: initUserinfo(), 
    menuRoutes: []
  }),

  actions: {
   

    async login (username: string, password: string) {
      try {
        let result = await userinfoApi.login({ username, password });
        // console.log('登录返回的数据', result);
        this.token = result.token; 
        setToken(result.token) // token 存到 localStorage
      } catch (error) {
        ElMessage.error('登录失败,请重试'); 
        return Promise.reject(error); 
      }
    },
    // 获取个人用户信息
    async getInfo () {
      try {
        let result = await userinfoApi.info(); 
        console.log('获取到的个人信息', result);
        this.userinfo = result; 
        // this.menuRoutes = staticRoutes// 用于侧边栏展示的,这里先写死,最终需要通过个人信息返回的权限信息进行修改

         //    参数一: 动态路由 - 动态路由就是需要筛选的路由
        //    参数二: 用户信息返回的当前用户可以看到的菜单
        //返回值是筛选完的路由数组
        const filterRoutes = filterRoutesHandler(cloneDeep(allAsyncRoutes), result.routes); // 筛选过后的路由
        const allRoutes = staticRoutes.concat(filterRoutes, anyRoute); // 任意路由必须放在所有路由的最后面
        this.menuRoutes = allRoutes

        addRoutes(allRoutes)//动态注册路哟
        
      } catch (error) {
        ElMessage.error('获取个人用户信息失败,请重试')
        return Promise.reject(error); 
      }
    },

    async logout () {
      try {
        let result = await userinfoApi.logout();
        this.reset(); // 调用actions中的reset函数,清除token和用户信息
      } catch (error) {
        ElMessage.error('退出登录失败,请重试')
        return Promise.reject(error);
      }
    },

    reset () {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.userinfo = initUserinfo()//初始化用户信息
    },
	},
});
